﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net 上传操作处理助手类    ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                    ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone               ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.IO;
using System.Web;
using Wedn.Net.Common;

namespace Wedn.Net.Utility
{
    /// <summary>
    /// 上传操作处理助手类
    /// </summary>
    public class Uploader
    {
        string _state = "SUCCESS";

        string _url;
        string _currentType;
        string _uploadPath;
        string _fileName;
        string _originalName;
        HttpPostedFile _uploadFile;

        /// <summary>
        /// 上传文件的主处理方法
        /// </summary>
        /// <param name="cxt">HTTP上下文</param>
        /// <param name="fileTypes">允许文件类型</param>
        /// <param name="size">允许文件大小</param>
        /// <returns></returns>
        public Hashtable UpFile(HttpContext cxt, string[] fileTypes, int size)
        {
            // 按月归档存储文件
            string basePath = Config.UploadRoot + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/";
            _uploadPath = cxt.Server.MapPath(Config.SiteRoot + basePath);//获取文件上传路径
            try
            {
                _uploadFile = cxt.Request.Files[0];
                _originalName = _uploadFile.FileName;
                //目录创建
                CreateFolder();
                //格式验证
                if (CheckType(fileTypes))
                {
                    _state = "不允许的文件类型";
                }
                //大小验证
                if (CheckSize(size))
                {
                    _state = "文件大小超出网站限制";
                }
                //保存图片
                if (_state == "SUCCESS")
                {
                    _fileName = ReName();
                    _uploadFile.SaveAs(_uploadPath + _fileName);
                    _url = basePath + _fileName;
                }
            }
            catch (Exception e)
            {
                _state = e.Message;//"未知错误";
                _url = string.Empty;
            }
            return GetUploadInfo();
        }

        /// <summary>
        /// 上传涂鸦的主处理方法
        /// </summary>
        /// <param name="cxt"></param>
        /// <param name="pathbase"></param>
        /// <param name="tmppath"></param>
        /// <param name="base64Data"></param>
        /// <returns></returns>
        public Hashtable UpScrawl(HttpContext cxt, string pathbase, string tmppath, string base64Data)
        {
            pathbase = pathbase + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            _uploadPath = cxt.Server.MapPath(Config.SiteRoot + pathbase);//获取文件上传路径
            FileStream fs = null;
            try
            {
                //创建目录
                CreateFolder();
                //生成图片
                _fileName = Guid.NewGuid() + ".png";
                fs = File.Create(_uploadPath + _fileName);
                byte[] bytes = Convert.FromBase64String(base64Data);
                fs.Write(bytes, 0, bytes.Length);

                _url = pathbase + _fileName;
            }
            catch (Exception e)
            {
                _state = e.Message;//"未知错误";
                _url = string.Empty;
            }
            finally
            {
                fs.Close();
                DeleteFolder(cxt.Server.MapPath(tmppath));
            }
            return GetUploadInfo();
        }

        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="cxt"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public string GetOtherInfo(HttpContext cxt, string field)
        {
            string info = null;
            if (cxt.Request.Form[field] != null && !String.IsNullOrEmpty(cxt.Request.Form[field]))
            {
                info = field == "fileName" ? cxt.Request.Form[field].Split(',')[1] : cxt.Request.Form[field];
            }
            return info;
        }

        /// <summary>
        /// 获取上传信息
        /// </summary>
        /// <returns></returns>
        private Hashtable GetUploadInfo()
        {
            var infoList = new Hashtable();

            infoList.Add("state", _state);
            infoList.Add("url", _url);

            if (_currentType != null)
                infoList.Add("currentType", _currentType);
            if (_originalName != null)
                infoList.Add("originalName", _originalName);
            return infoList;
        }

        /// <summary>
        /// 重命名文件
        /// </summary>
        /// <returns></returns>
        private string ReName()
        {
            //获取文件拓展名
            string ext = GetFileExt();
            return StringHelper.GetStreamMD5(_uploadFile.InputStream) + ext;
        }

        /// <summary>
        /// 文件类型检测
        /// </summary>
        /// <param name="filetype">文件允许类型拓展名数组</param>
        /// <returns></returns>
        private bool CheckType(string[] filetype)
        {
            _currentType = GetFileExt();
            return Array.IndexOf(filetype, _currentType) == -1;
        }

        /// <summary>
        /// 文件大小检测
        /// </summary>
        /// <param name="size">限制大小</param>
        /// <returns></returns>
        private bool CheckSize(int size)
        {
            return _uploadFile.ContentLength >= (size * 1024 * 1024);
        }

        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        private string GetFileExt()
        {
            return Path.GetExtension(_uploadFile.FileName);
        }

        /// <summary>
        /// 按照日期自动创建存储文件夹
        /// </summary>
        private void CreateFolder()
        {
            if (!Directory.Exists(_uploadPath))
            {
                Directory.CreateDirectory(_uploadPath);
            }
        }

        /// <summary>
        /// 删除存储文件夹
        /// </summary>
        /// <param name="path"></param>
        public void DeleteFolder(string path)
        {
            if (Directory.Exists(path))
            {
                Directory.Delete(path, true);
            }
        }
    }
}
